package org.jiuling.netty.test.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.jiuling.netty.handler.WebSocketHeartBeatHandler;

/**
 * 数据处理器
 * @author 紫灵
 * @date 2025年07月04日 10时10分58秒
 */
@ChannelHandler.Sharable
public class DataHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame frame) throws Exception {
        if (frame instanceof TextWebSocketFrame textWebSocketFrame) {
            String request = textWebSocketFrame.text();
            System.out.println("Received message: " + request);
            // 回复客户端
            channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("Server received: " + request));
        } else {
            String errorMessage = "Unsupported frame type: " + frame.getClass().getName();
            throw new UnsupportedOperationException(errorMessage);
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerAdded");
        super.handlerAdded(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            // 握手完成后发送欢迎消息
            ctx.channel().writeAndFlush(new TextWebSocketFrame(ctx.channel().id().asShortText()));
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }



    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("handlerRemoved");
        super.handlerRemoved(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        super.exceptionCaught(ctx, cause);
    }
}
